﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Oliving.Common.MyHelper
{
    public static class NetworkIHelper
    {

        public static string GetIP()
        {
            string result = "";
            foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces()
                    .Where(a => a.SupportsMulticast)
                    .Where(a => a.OperationalStatus == OperationalStatus.Up)
                    .Where(a => a.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                    .Where(a => a.GetIPProperties().GetIPv4Properties() != null)
                    .Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.Address.AddressFamily == AddressFamily.InterNetwork))
                    .Where(a => a.GetIPProperties().UnicastAddresses.Any(ua => ua.IsDnsEligible))
            )
            {
                Console.WriteLine("Network Interface: {0}", netif.Name);
                IPInterfaceProperties properties = netif.GetIPProperties();
                foreach (IPAddressInformation unicast in properties.UnicastAddresses)
                {
                    if (unicast.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Console.WriteLine("\tUniCast: {0}", unicast.Address);
                        return unicast.Address.ToString();
                    }
                }
            }
            return result;
        }


    }
}
